package com.iwhalecloud.bss.kite.cucc.web.service.scene;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.DcPublicConsts;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.LabelConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.constant.SwitchConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.flow.IPageFlowDefinitionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.flow.PageFlowDefinitionDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.flow.PageNavigationDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.PageNavigationReqDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.dataservice.entity.CuccKitePageNavigation;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.template.CuccKitePageNavigationMapper;
import com.iwhalecloud.bss.kite.cucc.web.service.accept.service.CuccKitePageNavigationCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferAttrCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.KitePageDefine;
import com.iwhalecloud.bss.kite.dataservice.entity.KitePageRelation;
import com.iwhalecloud.bss.kite.dataservice.entity.OfferAttr;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.dataservice.mapper.template.KitePageDefineMapper;
import com.iwhalecloud.bss.kite.dataservice.mapper.template.KitePageRelationMapper;
import com.iwhalecloud.bss.kite.dataservice.util.GeneralSwitchUtils;
import com.iwhalecloud.bss.kite.web.service.accept.service.KitePageNavigationCache;
import com.iwhalecloud.bss.kite.web.service.accept.vo.PageNavigationVO;
import com.iwhalecloud.bss.pub.client.constanst.Symbols;
import com.ztesoft.bss.base.staticdata.CoreDataPublic;
import com.ztesoft.bss.common.util.ContextUtil;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <Description> 页面导航 <br>
 *
 * @author huang.caibiao<br>
 * @version 1.0<br>
 * @taskId <br>
 * @date 2019-06-04 <br>
 * @see com.iwhalecloud.bss.kite.web.service.scene <br>
 * @since R9.0<br>
 */
@Service("localPageNavigationService")
public class PageNavigationService {

    @Autowired
    private CuccKitePageNavigationMapper kitePageNavigationMapper;

    @Autowired
    private KitePageRelationMapper kitePageRelationMapper;

    @Autowired
    private KitePageDefineMapper kitePageDefineMapper;

    @Autowired
    private IPageFlowDefinitionService pageFlowDefinitionService;

    /**
     * Description: <br>
     *
     * @param serviceOfferId 服务提供标识
     * @param offerType      销售品类型
     * @return 页面导航对象 <br>
     * @author huang.caibiao<br>
     * @taskId <br>
     */
    public PageNavigationVO getPageNavigation(String serviceOfferId, String tacheCode, String offerType, String objId) {
        PageNavigationVO resultVO = new PageNavigationVO();
        if (KiteStringUtils.isNoneBlank(serviceOfferId, tacheCode, offerType)) {
            String provinceNbr = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
            Example example = getCuccKitePageNavigationExample(serviceOfferId, tacheCode, offerType,
                objId, provinceNbr);
            CuccKitePageNavigation pageNavigation = kitePageNavigationMapper.selectOneByExample(example);
            if (Objects.isNull(pageNavigation)) {
                // 分省配置不同模块时，会查到多条数据报错
                // example = getCuccKitePageNavigationExample(serviceOfferId, tacheCode, offerType, objId, null);
                // pageNavigation = kitePageNavigationMapper.selectOneByExample(example);

                Map<String, String> params = new HashMap<>(8);
                params.put("serviceOfferId", serviceOfferId);
                params.put("tacheCode", tacheCode);
                params.put("offerType", offerType);
                params.put("objId", objId);
                params.put("statusCd", CoreDataPublic.PUB_C_0001_1000);
                pageNavigation = kitePageNavigationMapper.queryKitePageNavigation(params);
            }
            if (Objects.nonNull(pageNavigation)) {
                resultVO = KiteBeanUtils.transform(pageNavigation, PageNavigationVO.class);
                resultVO.setName(pageNavigation.getNavigationName());
                String navigationId = pageNavigation.getNavigationId();
                resultVO.setPageDefineList(listPageDefine(navigationId));
            }
        }

        return resultVO;
    }

    /**
     * 查询页面导航对象
     * @author zhang.song
     * @date 2022-01-21 10:48
     * @param serviceOfferId 服务提供标识
     * @param tacheCode
     * @param offerType 销售品类型
     * @param provinceNbr
     * @param objId
     * @return com.iwhalecloud.bss.kite.web.service.accept.vo.PageNavigationVO 页面导航对象
     */
    public PageNavigationVO getPageNavigation(String serviceOfferId, String tacheCode, String offerType, String provinceNbr, String objId) {
        PageNavigationVO resultVO = new PageNavigationVO();
        if (KiteStringUtils.isNoneBlank(serviceOfferId, tacheCode, offerType)) {
            CuccKitePageNavigation pageNavigation = null;
            if(KiteStringUtils.isNotEmpty(provinceNbr)) {
                Example example = getCuccKitePageNavigationExample(serviceOfferId, tacheCode, offerType, objId, provinceNbr);
                pageNavigation = kitePageNavigationMapper.selectOneByExample(example);
            }
            if (Objects.isNull(pageNavigation)) {
                Map<String, String> params = new HashMap<>(8);
                params.put("serviceOfferId", serviceOfferId);
                params.put("tacheCode", tacheCode);
                params.put("offerType", offerType);
                params.put("objId", objId);
                params.put("statusCd", CoreDataPublic.PUB_C_0001_1000);
                pageNavigation = kitePageNavigationMapper.queryKitePageNavigation(params);
            }
            if (Objects.nonNull(pageNavigation)) {
                resultVO = KiteBeanUtils.transform(pageNavigation, PageNavigationVO.class);
                resultVO.setName(pageNavigation.getNavigationName());
                String navigationId = pageNavigation.getNavigationId();
                resultVO.setPageDefineList(listPageDefine(navigationId));
            }
        }

        return resultVO;
    }

    private Example getCuccKitePageNavigationExample(String serviceOfferId, String tacheCode, String offerType,
                                                     String objId, String applyRegionCode) {
        Example example = new Example(CuccKitePageNavigation.class);
        Criteria criteria = example.createCriteria().andEqualTo("serviceOfferId", serviceOfferId).andEqualTo("tacheCode", tacheCode)
            .andEqualTo("offerType", offerType).andEqualTo("statusCd", CoreDataPublic.PUB_C_0001_1000);
        if (!KiteStringUtils.isEmpty(objId)) {
            criteria.andEqualTo("objId", objId);
        }
        else {
            criteria.andIsNull("objId");
        }

        if (!KiteStringUtils.isEmpty(applyRegionCode)) {
            criteria.andEqualTo("applyRegionCode", applyRegionCode);
        }
        return example;
    }

    /**
     * @param navigationId
     * @return
     */
    private PageNavigationVO getPageNavigationByNavId(String navigationId) {
        PageNavigationVO resultVO = new PageNavigationVO();
        CuccKitePageNavigation kitePageNavigation = new CuccKitePageNavigation();
        kitePageNavigation.setNavigationId(navigationId);
        kitePageNavigation.setStatusCd(CoreDataPublic.PUB_C_0001_1000);
        List<CuccKitePageNavigation> pageNavigations = kitePageNavigationMapper.select(kitePageNavigation);
        if (!KiteListUtils.isEmpty(pageNavigations)) {
            resultVO = KiteBeanUtils.transform(pageNavigations.get(0), PageNavigationVO.class);
            resultVO.setPageDefineList(listPageDefine(navigationId));
        }

        return resultVO;
    }

    /**
     * @param offerId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public PageNavigationVO getPageNavigationByOffer(String offerId, String serviceOfferId) {

        // 取分类ID
        String catId = null;
        List<OfferAttr> offerAttrs = OfferAttrCache.get(offerId);
        if (!KiteListUtils.isEmpty(offerAttrs)) {
            OfferAttr offerAttr = offerAttrs.stream().filter(attr -> "cateId".equals(attr.getFieldName())).findAny().orElse(new OfferAttr());
            catId = offerAttr.getDefaultValue();
        }
        // 优先根据offerId取页面导航配置
        List<DcPublic> dcPublicList = Lists.newArrayList();
        if (!KiteListUtils.isEmpty(DcPublicCache.getByPkey(DcPublicConsts.DC_190826999, offerId))) {
            dcPublicList.addAll(DcPublicCache.getByPkey(DcPublicConsts.DC_190826999, offerId));
        }
        if (!KiteListUtils.isEmpty(DcPublicCache.getByPkey(DcPublicConsts.DC_190826999, catId))) {
            dcPublicList.addAll(DcPublicCache.getByPkey(DcPublicConsts.DC_190826999, catId));
        }

        /*if (!KiteStringUtils.isEmpty(catId) && KiteListUtils.isEmpty(dcPublicList)) {
            dcPublicList = DcPublicCache.getByPkey(DcPublicConsts.DC_190826999, catId);
        }*/

        if (CollectionUtils.isNotEmpty(dcPublicList)) {
            DcPublic result = dcPublicList.stream().filter(dcPublic -> StringUtils.equals(serviceOfferId, dcPublic.getPcode())).findFirst().orElse(null);
            if (result != null && StringUtils.isNotBlank(result.getCodea())) {
                return getPageNavigationByNavId(result.getCodea());
            }
        }
        return null;
    }

    /**
     * 账户级销售品
     *
     * @param offerId
     * @param serviceOfferId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public PageNavigationVO getPageNavigationOfAcctOffer(String offerId, String serviceOfferId) {
        if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(serviceOfferId) && !ServiceOfferConsts.SERVICE_OFFER_MODIFY.equals(serviceOfferId)) {
            return null;
        }

        if (KiteStringUtils.isNotBlank(offerId)) {
            Offer offer = OfferCache.get(offerId);
            if (offer != null && KiteListUtils.isNotEmpty(offer.listAcctDetail())) {
                return KitePageNavigationCache.get(serviceOfferId, "1700");
            }
        }
        return null;
    }


    /**
     * Description: <br>
     *
     * @param navigationId
     * @return <br>
     * @author huang.caibiao<br>
     * @taskId <br>
     */
    private List<KitePageDefine> listPageDefine(String navigationId) {
        List<KitePageDefine> result = new ArrayList<>();
        KitePageRelation kitePageRelation = new KitePageRelation();
        kitePageRelation.setNavigationId(navigationId);
        kitePageRelation.setStatusCd(CoreDataPublic.PUB_C_0001_1000);
        List<KitePageRelation> kitePageRelations = kitePageRelationMapper.select(kitePageRelation);
        getPageDefine(kitePageDefineMapper.getFromDefineId(navigationId), kitePageRelations, result);

        return result;
    }

    /**
     * Description: <br>
     *
     * @param fromDefineId
     * @param kitePageRelations
     * @param result            <br>
     * @author huang.caibiao<br>
     * @taskId <br>
     */
    private void getPageDefine(String fromDefineId, List<KitePageRelation> kitePageRelations,
                               List<KitePageDefine> result) {
        if (KiteStringUtils.isNotBlank(fromDefineId)) {
            result.add(kitePageDefineMapper.selectByPrimaryKey(fromDefineId));
        }
        for (KitePageRelation pageRelation : kitePageRelations) {
            if (KiteStringUtils.equals(fromDefineId, pageRelation.getFromDefineId())
                && KiteStringUtils.isNoneBlank(pageRelation.getToDefineId())) {
                getPageDefine(pageRelation.getToDefineId(), kitePageRelations, result);
            }
        }
    }

    /**
     * 获取父子合约销售品的页面导航
     *
     * @param offerId
     * @param serviceOfferId
     * @return
     */
    public PageNavigationVO getPageNavOfContractOffer(String offerId, String serviceOfferId) {
        if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(serviceOfferId) && !ServiceOfferConsts.SERVICE_OFFER_MODIFY.equals(serviceOfferId)) {
            return null;
        }
        if (KiteStringUtils.isNotBlank(offerId)) {
            Offer offer = OfferCache.get(offerId);
            if (offer != null) {
                if (KeyConsts.OFFER_TYPE_13.equals(offer.getOfferType()) && KeyConsts.OFFER_SYS_TYPE_1599.equals(offer.getOfferSysType())) {
                    return KitePageNavigationCache.get(serviceOfferId, KeyConsts.OFFER_SYS_TYPE_1599);
                }
            }
        }
        return null;
    }


    /**
     * <Description> <br>
     * 获取政企类带宽型业务导航；
     *
     * @author TinaYuzuKi<br>
     * @version 1.0<br>
     * @taskId <br>
     * @CreateDate 2019年12月22日 下午4:50:35 <br>
     * @since V0.1<br>
     **/
    public PageNavigationVO getBandWidthOffer(String offerId, String serviceOfferId) {
        if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(serviceOfferId) && !ServiceOfferConsts.SERVICE_OFFER_MODIFY.equals(serviceOfferId)) {
            return null;
        }
        if (KiteStringUtils.isNotBlank(offerId)) {
            Offer offer = OfferCache.get(offerId);
            if (offer != null) {
                if (KeyConsts.OFFER_TYPE_10.equals(offer.getOfferType()) && offer.hasLabel(LabelConsts.LABEL_CODE_BANDWIDTH)) {
                    return KitePageNavigationCache.get(serviceOfferId, LabelConsts.LABEL_CODE_BANDWIDTH);
                }
            }
        }
        return null;
    }

    /**
     * 低代码平台页面流解析
     *
     * @param reqDTO 页面流请求对象
     * @return 页面流对象
     */
    public PageNavigationVO parseLcdpPageDefinition(PageNavigationReqDTO reqDTO) {
        PageNavigationVO pageNavigationVO = new PageNavigationVO();
        String serviceOfferId = reqDTO.getServiceOfferId();
        /**
         * 二级研发查找页面流时增加服务提供映射
         */
        DcPublic serviceOfferConvert = DcPublicCache.get("20211127103000", serviceOfferId);
        if( serviceOfferConvert!=null&&serviceOfferConvert.getPcode()!=null ){
            serviceOfferId = serviceOfferConvert.getPcode();
        }

        if (KiteStringUtils.isNotBlank(serviceOfferId)&&KiteStringUtils.equals(serviceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_TRANSFER_CUST_SALE)) {
            serviceOfferId = LocalServiceOfferConsts.SERVICE_OFFER_TRANSFER_CUST;
        }
        pageNavigationVO.setServiceOfferId(serviceOfferId);
        String cateId = reqDTO.getCateId();
        String objId = reqDTO.getObjId();
        String tacheCode = reqDTO.getTacheCode();
        String offerType = reqDTO.getOfferType();

        Offer offer = OfferCache.get(objId);
        if (Objects.nonNull(offer)) {
            offerType = offer.getOfferType();
            if (KiteStringUtils.isEmpty(cateId)) {
                cateId = offer.getCateId();
            }
            if (KiteStringUtils.isEmpty(cateId)) {
                List<OfferAttr> offerAttrs = OfferAttrCache.get(objId);
                if (KiteStringUtils.isEmpty(objId) && !KiteListUtils.isEmpty(offerAttrs)) {
                    OfferAttr catIdAttr = offerAttrs.stream().filter(attr -> "cateId".equals(attr.getFieldName()))
                        .findAny().orElse(new OfferAttr());
                    objId = catIdAttr.getDefaultValue();
                }
            }

        }

        PageFlowDefinitionDTO pageFlowDefinitionDTO = null;
        if (GeneralSwitchUtils.isSwitchOpened("PAGE_FLOW_QRY_OPTIMIZE")) {
            pageFlowDefinitionDTO = pageFlowDefinitionService.getPageFlowDefinitionNew(serviceOfferId, cateId, objId, tacheCode);
        }
        else {
            pageFlowDefinitionDTO = pageFlowDefinitionService.getPageFlowDefinition(serviceOfferId, cateId, objId, tacheCode);
        }

        if (Objects.nonNull(pageFlowDefinitionDTO)) {
            PageNavigationDTO pageNavigationDTO = pageFlowDefinitionService.transferLcdpPageNavigation(serviceOfferId, objId, offerType, tacheCode, pageFlowDefinitionDTO);
            if (Objects.isNull(pageNavigationDTO)) {
                return pageNavigationVO;
            }
            KiteBeanUtils.copyProperties(pageNavigationDTO, pageNavigationVO);
            String key = KiteStringUtils.join(serviceOfferId, Symbols.UNDERLINE, tacheCode, Symbols.UNDERLINE, offerType);
            if (!KiteStringUtils.isEmpty(objId)) {
                key = KiteStringUtils.join(key, Symbols.UNDERLINE, objId);
            }
            // 设置入缓存
            CuccKitePageNavigationCache.getInst().defaultPut(key, pageNavigationVO);
        }
        return pageNavigationVO;
    }

    public DataResult<PageNavigationVO> getPageNavigationVO(PageNavigationReqDTO reqDTO) {
        // 1、先根据任务编码获取（环节编码不满足一个环节多个任务的模板配置要求） 先优先取Offer_id下的配置
        String serviceOfferId = reqDTO.getServiceOfferId();

        String tacheCode = reqDTO.getTacheCode();

        String offerType = reqDTO.getOfferType();

        String objId = reqDTO.getObjId();

        // 为空则认为是录入
        if (KiteStringUtils.isEmpty(tacheCode)) {
            tacheCode = "OrderInput";
        }

        // 1、根据商品ID来获取，获取不到，则先根据商品分类来获取，优先取分类下的配置
        // 根据商品ID来获取，优先取商品下的配置 obj_id 可以是分类ID，也可以是offer_id

        PageNavigationVO pageNavigationVO = CuccKitePageNavigationCache
            .get(serviceOfferId, tacheCode, offerType, objId);

        // 2，不存在，则获取，service_offer_id为-1的数据，即表示相同商品，不同业务，不同环节都用同一个模版
        if (Objects.isNull(pageNavigationVO) || KiteStringUtils.isEmpty(pageNavigationVO.getNavigationId())) {
            pageNavigationVO = CuccKitePageNavigationCache.get("-1", tacheCode, offerType, objId);
        }
        // 3、不存在，则获取obj_id为空的数据，即表示所有商品同一业务，不同环节都用同一个模版
        if (Objects.isNull(pageNavigationVO) || KiteStringUtils.isEmpty(pageNavigationVO.getNavigationId())) {
            pageNavigationVO = CuccKitePageNavigationCache.get(serviceOfferId, tacheCode, offerType, null);
        }
        //添加低代码平台控制页面流开关
        if (GeneralSwitchUtils.isSwitchOpened(SwitchConsts.CHECK_LCDP_PAGE_FLOW)) {
            if (Objects.isNull(pageNavigationVO) || KiteStringUtils.isEmpty(pageNavigationVO.getNavigationId())) {
                //处理低代码平台解析页面流
                pageNavigationVO = this.parseLcdpPageDefinition(reqDTO);
            }
        }

        // 4，不存在，则获取，service_offer_id为-1，obj_id为空的数据的数据，即表示所有商品不同业务，不同环节，不同商品都用同一个模版
        if (Objects.isNull(pageNavigationVO) || KiteStringUtils.isEmpty(pageNavigationVO.getNavigationId())) {
            pageNavigationVO = CuccKitePageNavigationCache.get("-1", tacheCode, offerType, null);
        }

        if (Objects.nonNull(pageNavigationVO) && KiteStringUtils.isNotEmpty(pageNavigationVO.getNavigationId())) {
            pageNavigationVO.setPageType(DcPublicCache.getCodea("20201202001", tacheCode));
            return ErrorConsts.SUCCESS.getResult(pageNavigationVO);
        }
        return ErrorConsts.SUCCESS.getResult(null);
    }

    private DataResult<PageNavigationVO> getPageNavigationVOByOfferId(String serviceOfferId, String tacheCode, String offerType, String offerId) {
        // 1、根据商品ID来获取，获取不到，则先根据商品分类来获取，优先取分类下的配置
        // 根据商品ID来获取，优先取商品下的配置 obj_id 为offer_id

        PageNavigationVO pageNavigationVO = CuccKitePageNavigationCache
            .get(serviceOfferId, tacheCode, offerType, offerId);

        // 2，不存在，则获取，service_offer_id为-1的数据，即表示相同商品，不同业务，不同环节都用同一个模版
        if (Objects.isNull(pageNavigationVO) || KiteStringUtils.isEmpty(pageNavigationVO.getNavigationId())) {
            pageNavigationVO = CuccKitePageNavigationCache.get("-1", tacheCode, offerType, offerId);
        }

        if (Objects.nonNull(pageNavigationVO) && KiteStringUtils.isNotEmpty(pageNavigationVO.getNavigationId())) {
            pageNavigationVO.setPageType(DcPublicCache.getCodea("20201202001", tacheCode));
            return ErrorConsts.SUCCESS.getResult(pageNavigationVO);
        }
        return ErrorConsts.SUCCESS.getResult(null);
    }

}
